<template>
  <div class="redirect">
    <t-loading size="medium" :loading="loading" show-overlay></t-loading>
    <!-- 邮箱采集 -->
    <collect-info v-model="collectVisible" @done="redirectTo" @cancel="redirectTo" />
  </div>
</template>
<script lang="ts" setup>
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import CollectInfo from '@/components/collect-info/index.vue';
import { oauth } from '@/api/auth';
import { useUserStore } from '@/store';

const userStore = useUserStore();

const route = useRoute();
const router = useRouter();

const collectVisible = ref(false);

const loading = ref(true);

const getAuthForApp = async () => {
  try {
    // 授权成功有两种情况
    // 1.需要补充邮件 qq, wx 需要补充邮件
    // 2.不需要补充直接登录
    const authResult = await oauth(route.params?.app as string, route?.query);
    console.log('authResult', authResult);
    if (authResult) {
      userStore.oauthLogin(authResult);
      // 检查Email，如果不是就需要用户补充
      const regExpRule = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!regExpRule.test(userStore?.userInfo?.email)) {
        MessagePlugin.success('授权成功');
        MessagePlugin.warning('请您添加邮件信息，以便信息及时推送');
        // 展示弹窗
        collectVisible.value = true;
      } else {
        MessagePlugin.success('登录成功');
        redirectTo();
      }
    }
  } catch (err) {
    MessagePlugin.error(`授权登录失败：${err.message}`);
    // 直接错误返回首页
    router.replace('/');
  }
};

const redirectTo = () => {
  const redirect = route.query.redirect as string;
  const redirectUrl = redirect ? decodeURIComponent(redirect) : '/overview';
  router.push(redirectUrl);
};

onMounted(async () => {
  if (route.params?.app) {
    getAuthForApp();
  }
});
</script>
<style lang="less" scoped>
.redirect {
  position: relative;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
